require("View")

MindsView = class("MindsView", View)

---

function MindsView:initialize()

	View.initialize(self)
	
	self.rootWindow = wx.wxTreeCtrl( 
		gView.frame, 
		wx.wxID_ANY,
        wx.wxDefaultPosition, 
        wx.wxSize(-1, -1),
        wx.wxTR_LINES_AT_ROOT + wx.wxTR_HAS_BUTTONS
    )     
        
	self.rootId = self.rootWindow:AddRoot( "Minds" )
end

---

function MindsView:update()

	self.rootWindow:DeleteChildren(self.rootId)
	
	for mindName, mindEntity in pairs(gField.entityTypes.Mind) do
	
		self:addMind(mindEntity, self.rootId)
	end	

	self.rootWindow:Expand(self.rootId)
end

---

function MindsView:addMind(mindEntity, parentID)

	local mindsId = self.rootWindow:AppendItem(parentID, mindEntity.name )
	
	if mindEntity.behavior
	then
		self:addGoal(mindsId, mindEntity.behavior.rootGoal)
	end	
end

---

function MindsView:addGoal(parentID, goal)
	
	local goalId = self.rootWindow:AppendItem(parentID, "[ " .. goal.name .. " ]" )
	
	
	-- variables
	
	if next(goal.variables)
	then
		self:addTable(goalId, "variables", goal.variables)
	end
	
	
	-- causes
	
	if goal.causes
	then
		for i, cause in ipairs(goal.causes)
		do
			self.rootWindow:AppendItem(goalId, "cause: " .. tostring(cause))
		end
	end

	
	-- effects
	
	if goal.effects
	then
		for i, effect in ipairs(goal.effects)
		do
			self.rootWindow:AppendItem(goalId, "effect: " .. tostring(effect))
		end
	end
	
	
	-- sub goals
	
	for subGoalName, subGoal in pairs(goal.subGoals) 
	do
		self:addGoal(goalId, subGoal)
	end

	self.rootWindow:Expand(goalId)
end

---

function MindsView:addTable(parentID, tableName, table)

	local tableID = self.rootWindow:AppendItem(parentID, tableName)
	
	for variableName, variableValue in pairs(table)
	do
		if 
			(type(variableValue) == "table") and
			not variableValue.isEntity
		then
			self:addTable(tableID, variableName, variableValue)
		else
			local variableValueString
			if variableValue.isEntity
			then
				variableValueString = variableValue.type .. " " .. variableValue.name
			else
				variableValueString = tostring(variableValue)
			end
			self.rootWindow:AppendItem(tableID, variableName.. ": " .. variableValueString)
		end
	end
end
